package org.apache.servicecomb.samples.practise.houserush.sale.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
@Entity
@Table(name = "sales")
@EntityListeners(AuditingEntityListener.class)
//活动使用逻辑删除
@SQLDelete(sql = "update sales set deleted_at = now() where id = ?")
@Where(clause = "deleted_at is null")
public class Sale {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    private String state = "new";

    @Temporal(TemporalType.TIMESTAMP)
    private Date beginAt;

    @Temporal(TemporalType.TIMESTAMP)
    private Date endAt;

    private Integer realestateId;

    //活动名称
    @Transient
    private String realestateNme;

    @OneToMany(mappedBy = "sale")
    @Fetch(FetchMode.JOIN)
    @JsonIgnoreProperties(ignoreUnknown = true, value = {"sale"})
    private List<HouseOrder> houseOrders = new ArrayList<>();

//    @Temporal(TemporalType.TIMESTAMP)
//    private Date orderedAt;
    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;

    //活动有三种状态
    //发布成功
    //开售中
    //发售结束
    //根据活动的开始时间和结束时间判断活动状态
    public String getState() {
        Date now = new Date();
        if(now.getTime() < beginAt.getTime()) {
            return "published";
        } else if(now.getTime() >= beginAt.getTime() && now.getTime() <= endAt.getTime()) {
            return "opening";
        } else {
            return "finished";
        }
    }

    @Override
    public String toString() {
        return "Sale{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", state='" + state + '\'' +
                ", beginAt=" + beginAt +
                ", endAt=" + endAt +
                ", realestateId=" + realestateId +
                ", realestateNme='" + realestateNme + '\'' +
                ", houseOrders=" + houseOrders +
                ", createdAt=" + createdAt +
                ", updatedAt=" + updatedAt +
                '}';
    }
}

